<template>
  <div id="app">
    <el-row type="flex" justify="center">
      <el-col :span="8">
        <h3>用户登录(04)</h3>
        <el-divider></el-divider>
        <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="ruleForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="pass">
            <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  data() {
    var checkUsername = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('用户名不能为空'));
      }
      callback();
    };
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      }
      callback();
    };
    return {
      ruleForm: {
        pass: '',
        username: ''
      },
      rules: {
        pass: [
          {validator: validatePass, trigger: 'blur'}
        ],
        username: [
          {validator: checkUsername, trigger: 'blur'}
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = 'http://localhost:18080/user/login';
          console.log('请求路径：' + url);
          let data1 = {
            "password": this.ruleForm.pass,
            "username": this.ruleForm.username
          };
          console.log('请求参数：');
          console.log(data1);
          this.axios.post(url, data1)
              .then((response) =>{
                console.log(response);
                let json = response.data;
                let state = json.state;
                if (state == 200) {
                  console.log('登录成功！');
                  this.$message({
                    message: '登录成功！',
                    type: 'success'
                  });
                } else {
                  console.log(json.message);
                  this.$message.error(json.message);
                }
              })
              .catch(function (error) {
                console.log(error);
              });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>